<?php
namespace Home\Controller;
use Think\Controller;

/**
 * 公告控制
 */
class AnnounceController extends Controller {
	//全局变量区
	/**
	 * 用户权限类型
	 * 1：普通用户
	 */
	public $user_access_type_normal = 1;
	/**
	 * 删除公告结果
	 * 0：删除成功
	 * 1：权限不足
	 * 2：公告不存在
	 */
	public $delete_announce_result_success = 0;
	public $delete_announce_result_access = 1;
	public $delete_announce_result_not_exist = 2;
	/**
	 * 布局相关
	 * list_each_page_number：每一页列表条数
	 */
	public $list_each_page_number = 5;

	/**
	 * 进入公告页面
	 */
	public function index(){
		$announcements = M('announcement_table');
		$result = $announcements->count();
		$this->assign('announce_count', $result);
		$this->display();
	}

	/**
	 * 公告查询
	 */
	public function announceSearch(){
		//前端传输数据
		//0：系统公告 1：球馆公告 2：教练公告 3:球会公告 -1：不限
		$search_type = $_POST['search_type'];
		$search_info = $_POST['search_info'];
		//实例化公告对象
		$announcements = M('announcement_table');
		//位置信息
		$e_page_num = $this->list_each_page_number;  //每一页的公告条数
		$page_num = 1;  //页数

		//位置信息获取并置位
		if($_POST['search_page_num']){
			$page_num = $_POST['search_page_num'];
		}
		$start_p = $e_page_num * ($page_num - 1);

		//实例化查询条件数组
		$search_info = "%".$search_info;
		$where['announce_title'] = array('like', $search_info."%");
		if($search_type != -1){
			$where['announce_type'] = $search_type;
		}
		$where['if_public'] = 1;

		//进行查询
		$result = $announcements->where($where)->order('announce_time DESC')->limit($start_p, $e_page_num)->select();
		$announceCount = $announcements->where($where)->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['announce_count'] = $announceCount;
		$this->ajaxReturn($resultList);
	}

	/**
	 * 按时间顺序输出所有公告
	 * 公告页控制器
	 */
	public function announceTimeOrderPublish(){
		//前端传输数据，明确分页情况
		$e_page_num = $this->list_each_page_number;  //每一页的公告条数
		$page_num = $_POST['page_num'];  //页数

		//实例化公告对象
		$announcements = M('announcement_table');
		$start_p = $e_page_num * ($page_num - 1);

		//进行查询
		$where['if_public'] = 1;
		$result = $announcements->where($where)->order('announce_time DESC')->limit($start_p, $e_page_num)->select();
		$announceCount = $announcements->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['announce_count'] = $announceCount;
		$this->ajaxReturn($resultList);
	}

	/**
	 * 我发布的公告列表
	 */
	public function myAnnounceTimeOrderPublish(){
		//前端传输数据，明确分页情况
		$e_page_num = $this->list_each_page_number;  //每一页的公告条数
		$page_num = $_POST['page_num'];  //页数
		$user_id = session('id');  //从session中获取用户id

		//实例化公告对象
		$announcements = M('announcement_table');
		$start_p = $e_page_num * ($page_num - 1);

		//进行查询
		$where['publisher_id'] = $user_id;
		$result = $announcements->where($where)->order('announce_time DESC')->limit($start_p, $e_page_num)->select();
		$announceCount = $announcements->where($where)->count();

		//ajax返回
		$resultList['result'] = $result;
		$resultList['page_num'] = $page_num;
		$resultList['announce_count'] = $announceCount;
		$this->ajaxReturn($resultList);
	}

	/**
	 * 创建公告 
	 */
	public function announce_create(){
        //加载当前用户信息
        $user=$_SESSION['think_'];
        $this->assign('user',$user);

        //设置当前的选项位置（即该选项为橙色)   
        $this->assign("biz_item_num",5);
        $this->display();
	}
	//教练公告创建
	public function coach_announce_create()
	{
		 $user=$_SESSION['think_'];
        $this->assign('user',$user);
        //设置当前的选项位置（即该选项为橙色)   
        $this->assign("biz_item_num",5);
        $this->display();
	}
	//球馆公告创建控制器
	public function gymnasium_create_announce_handler()
	{
        $announce=M('announcement_table');
        $gym_announce=M('announcement_gymnasium_table');
		$user=M('user_table');
        if (session('id'))
		{
		  	$user_id=session('id');		
			if (!$_POST['announce_title']) {$this->error("标题不能为空");};
			if (!$_POST['announce_content']) {$this->error("内容不能为空");};
			$data['announce_title']=$_POST['announce_title'];	
			$data['announce_content']=$_POST['announce_content'];
			$data['announce_time']=date("y-m-d H:i:s");
			$data['publisher_id']=$user_id;
			$data['announce_type']=1;
			$data['if_public']=1;
			$upload = new \Org\Net\UploadFile();
          	$upload->maxSize = 3145728;
          	//设置文件上传类型  
          	$upload->allowExts = array('jpg','gif','png','jpeg');  
          	//设置文件上传位置  
          	//$upload->savePath = __PUBLIC__."/Img/Uploads/";
          	$upload->savePath = "./Public/Img/Uploads/announceImg/";  
          	//设置文件上传名(按照时间)  
          	$upload->saveRule = "time";
          	if (!$upload->upload()){  
              	//$resultList['result'] = $upload->getErrorMsg();
              	$this->error($upload->getErrorMsg());
			}
			$info = $upload->getUploadFileInfo();
              	$savename = $info[0]['savename'];
          	  	$imgurl = "__PUBLIC__/Img/Uploads/announceImg/".$savename;
          	  	$data['announce_picture'] = $imgurl;
			if ($announce->add($data))
			{
				$gym_info['g_announce_id']=$announce->order('announce_id desc')->limit(1)->getField('announce_id');
				$gym_info['g_gymnasium_id']=$_POST['gymnasium_id'];
				
				$gym_announce->add($gym_info);
				$this->success("发布成功");
			};
		}
		else{
			$this->error("请先登录");
		}
         		
	}
	//教练公告创建控制器
	public function coach_create_announce_handler()
	{
        $announce=M('announcement_table');
      
        $coach_announce=M('announcement_coach_table');
        
		$user=M('user_table');
        if (session('id'))
		{
		  	$user_id=session('id');
			
			$access=$user->where("id=%d",$user_id)->getField('access');
			if ($access!=3 || $access!=5 || $access!=6 || $access!=7){$this->error("非教练不能发布教练公告");}
			if (!$_POST['announce_title']) {$this->error("标题不能为空");};
			if (!$_POST['announce_content']) {$this->error("内容不能为空");};
		
			$data['announce_title']=$_POST['announce_title'];	
			$data['announce_content']=$_POST['announce_content'];
			$data['announce_time']=date("y-m-d H:i:s");
			$data['publisher_id']=$user_id;
			$data['announce_type']=2;
			$data['if_public']=1;
			$upload = new \Org\Net\UploadFile();
          	$upload->maxSize = 3145728;
          	//设置文件上传类型  
          	$upload->allowExts = array('jpg','gif','png','jpeg');  
          	//设置文件上传位置  
          	//$upload->savePath = __PUBLIC__."/Img/Uploads/";
          	$upload->savePath = "./Public/Img/Uploads/announceImg/";  
          	//设置文件上传名(按照时间)  
          	$upload->saveRule = "time";
          	if (!$upload->upload()){  
              	//$resultList['result'] = $upload->getErrorMsg();
              	$this->error($upload->getErrorMsg());
			}
			$info = $upload->getUploadFileInfo();
              	$savename = $info[0]['savename'];
          	  	$imgurl = "__PUBLIC__/Img/Uploads/announceImg/".$savename;
          	  	$data['announce_picture'] = $imgurl;
			if ($announce->add($data))
			{
				$coach_info['c_announce_id']=$announce->order('announce_id desc')->limit(1)->getField('announce_id');
				$coach_info['c_coach_id']=session('id');
				
				$coach_announce->add($coach_info);
				$this->success("发布成功");
			};
		}
		else{
			$this->error("请先登录");
		}
         		
	}
	//球会公告创建控制器
    public function club_create_announce_handler()
	{
        $announce=M('announcement_table');
        $club_announce=M('announcement_club_table');
     
		$user=M('user_table');
        if (session('id'))
		{
		  	$user_id=session('id');
			
			$access=$user->where("id=%d",$user_id)->getField('access');
			
			if (!$_POST['announce_title']) {$this->error("标题不能为空");};
			if (!$_POST['announce_content']) {$this->error("内容不能为空");};
			
			$data['announce_title']=$_POST['announce_title'];	
			$data['announce_content']=$_POST['announce_content'];
			$data['announce_time']=date("y-m-d H:i:s");
			$data['publisher_id']=$user_id;
			$data['announce_type']=3;
			$data['if_public']=$_POST['if_public'];
			$upload = new \Org\Net\UploadFile();
          	$upload->maxSize = 3145728;
          	//设置文件上传类型  
          	$upload->allowExts = array('jpg','gif','png','jpeg');  
          	//设置文件上传位置  
          	//$upload->savePath = __PUBLIC__."/Img/Uploads/";
          	$upload->savePath = "./Public/Img/Uploads/announceImg/";  
          	//设置文件上传名(按照时间)  
          	$upload->saveRule = "time";
          	if (!$upload->upload()){  
              	//$resultList['result'] = $upload->getErrorMsg();
              	$this->error($upload->getErrorMsg());
			}
			$info = $upload->getUploadFileInfo();
              	$savename = $info[0]['savename'];
          	  	$imgurl = "__PUBLIC__/Img/Uploads/announceImg/".$savename;
          	  	$data['announce_picture'] = $imgurl;
			if ($announce->add($data))
			{
				$club_info['c_announce_id']=$announce->order('announce_id desc')->limit(1)->getField('announce_id');
				$club_info['c_club_id']=$_POST['club_id'];
				$club_info['if_public']=$data['if_public'];
				 /* dump($club_info);
				return;  */
				$club_announce->add($club_info);
				$this->success("发布成功");
			};
		}
		else{
			$this->error("请先登录");
		}
         		
	}
	/**
	 * 创建公告 球会
	 * 返回值：
	 *     字段自动检测错误：相应错误信息
	 *     添加失败：返回3
	 *     添加成功：返回0
	 *     图片上传失败：返回对应错误信息
	 */
	public function clubAnnounceCreateHandeler(){
		//实例化球会对象
		$announce = D('AnnouncementTable');
		//实例化公告球会对照对象
		$announceClub = M('announcement_club_table');

		//从前端获取球会id
		$clubId = $_POST['club_id'];

		// 自动验证 创建数据集
        if (!$data = $announce->create()) {
            // 防止输出中文乱码
            header("Content-type: text/html; charset=utf-8");
            $resultList['result'] = $announce->getError();
        }else{
        	//自动验证完成，接收上传图片
        	//实例化上传类
          	$upload = new \Org\Net\UploadFile();
          	$upload->maxSize = 3145728;
          	//设置文件上传类型  
          	$upload->allowExts = array('jpg','gif','png','jpeg');  
          	//设置文件上传位置  
          	//$upload->savePath = __PUBLIC__."/Img/Uploads/";
          	$upload->savePath = "./Public/Img/Uploads/announceImg/";  
          	//设置文件上传名(按照时间)  
          	$upload->saveRule = "time";
          	if (!$upload->upload()){  
              	//$resultList['result'] = $upload->getErrorMsg();
              	$this->error($upload->getErrorMsg());  
          	}else{  
              	//上传成功，获取上传信息  
              	$info = $upload->getUploadFileInfo();
              	$savename = $info[0]['savename'];
          	  	$imgurl = "__PUBLIC__/Img/Uploads/announceImg/".$savename;
          	  	$data['announce_picture'] = $imgurl;
          	  	$data['publisher_id'] = session('id');
          	  	//$data['announce_time'] = date("y-m-d H:i:s");
          	  	$data['announce_type'] = 3;

          	  	//添加公告
        		$result = $announce->add($data);
        		if(!$result){
        			$resultList['result'] = 3;
        		}else{
        			$announceClubData['c_announce_id'] = $result;
        			$announceClubData['c_club_id'] = $clubId;
        			$announceClubData['if_public'] = $data['if_public'];
        			$addAnnounceClub = $announceClub->add($announceClubData);

        			$resultList['result'] = 0;
        		}
          	}	
        }

        $this->ajaxReturn($resultList);
	}

	/**
	 * 创建公告 球馆
	 * 返回值：
	 *     字段自动检测错误：相应错误信息
	 *     添加失败：返回3
	 *     添加成功：返回0
	 *     图片上传失败：返回对应错误信息
	 */
	public function gymnasiumAnnounceCreateHandeler(){
		//实例化球会对象
		$announce = D('AnnouncementTable');
		//实例化球馆公告对照对象
		$announceGymnasium = M('announcement_gymnasium_table');

		//从前端获取球馆id
		$gymnasiumsId = $_POST['gymnasium_id'];

		// 自动验证 创建数据集
        if (!$data = $announce->create()) {
            // 防止输出中文乱码
            header("Content-type: text/html; charset=utf-8");
            $resultList['result'] = $announce->getError();
        }else{
        	//自动验证完成，接收上传图片
        	//实例化上传类
          	$upload = new \Org\Net\UploadFile();
          	$upload->maxSize = 3145728;
          	//设置文件上传类型  
          	$upload->allowExts = array('jpg','gif','png','jpeg');  
          	//设置文件上传位置  
          	//$upload->savePath = __PUBLIC__."/Img/Uploads/";
          	$upload->savePath = "./Public/Img/Uploads/announceImg/";  
          	//设置文件上传名(按照时间)  
          	$upload->saveRule = "time";
          	if (!$upload->upload()){  
              	$resultList['result'] = $upload->getErrorMsg();   
          	}else{  
              	//上传成功，获取上传信息  
              	$info = $upload->getUploadFileInfo();
              	$savename = $info[0]['savename'];
          	  	$imgurl = "__PUBLIC__/Img/Uploads/announceImg/".$savename;
          	  	$data['announce_picture'] = $imgurl;
          	  	$data['publisher_id'] = session('id');
          	  	$data['announce_time'] = date("y-m-d H:i:s");
          	  	$data['announce_type'] = 1;

          	  	//添加公告
        		$result = $announce->add($data);
        		if(!$result){
        			$resultList['result'] = 3;
        		}else{
        			$announceGymnasiumData['g_announce_id'] = $result;
        			$announceGymnasiumData['g_gymnasium_id'] = $gymnasiumsId;
        			$addAnnounceGymnasium = $announceGymnasium->add($announceGymnasiumData);

        			$resultList['result'] = 0;
        		}
          	}	
        }

        $this->ajaxReturn($resultList);
	}

	/**
	 * 创建公告 教练
	 * 返回值：
	 *     字段自动检测错误：相应错误信息
	 *     添加失败：返回3
	 *     添加成功：返回0
	 *     图片上传失败：返回对应错误信息
	 */
	public function coachAnnounceCreateHandeler(){
		//实例化球会对象
		$announce = D('AnnouncementTable');
		//实例化公告教练对照对象
		$announceCoach = M('announcement_coach_table');

		// 自动验证 创建数据集
        if (!$data = $announce->create()) {
            // 防止输出中文乱码
            header("Content-type: text/html; charset=utf-8");
            $resultList['result'] = $announce->getError();
        }else{
        	//自动验证完成，接收上传图片
        	//实例化上传类
          	$upload = new \Org\Net\UploadFile();
          	$upload->maxSize = 3145728;
          	//设置文件上传类型  
          	$upload->allowExts = array('jpg','gif','png','jpeg');  
          	//设置文件上传位置  
          	//$upload->savePath = __PUBLIC__."/Img/Uploads/";
          	$upload->savePath = "./Public/Img/Uploads/announceImg/";  
          	//设置文件上传名(按照时间)  
          	$upload->saveRule = "time";
          	if (!$upload->upload()){  
              	$resultList['result'] = $upload->getErrorMsg();  
          	}else{  
              	//上传成功，获取上传信息  
              	$info = $upload->getUploadFileInfo();
              	$savename = $info[0]['savename'];
          	  	$imgurl = "__PUBLIC__/Img/Uploads/announceImg/".$savename;
          	  	$data['announce_picture'] = $imgurl;
          	  	$data['publisher_id'] = session('id');
          	  	$data['announce_time'] = date("y-m-d H:i:s");
          	  	$data['announce_type'] = 2;

          	  	//添加公告
        		$result = $announce->add($data);
        		if(!$result){
        			$resultList['result'] = 3;
        		}else{
        			$announceCoachData['c_announce_id'] = $result;
        			$announceCoachData['c_coach_id'] = session('id');
        			$addAnnounceCoach = $announceCoach->add($announceCoachData);

        			$resultList['result'] = 0;
        		}
          	}	
        }

        $this->ajaxReturn($resultList);
	}

	/**
	 * 删除公告 球会
	 * 返回值：
	 *     delete_announce_result_not_exist
	 *     delete_announce_result_access
	 *     delete_announce_result_success
	 */
	public function clubdeleteAnnounce(){
		//前端传输数据，获取公告id
		$announce_id = $_POST['announce_id'];

		//实例化公告球会对照对象
		$announceClub = M('announcement_club_table');

		//从session获取用户id
		$userId = session('id');

		//删除对应公告
		$where['announce_id'] = $announce_id;
		$count = $user->where($where)->count();
		$where['publisher_id'] = $userId;
		$deleteResult = $user->where($where)->delete();

		if($count == 0){
			$resultList['delete_announce_result'] = $this->delete_announce_result_not_exist;
		}else{
			if(!$deleteResult){
				//权限不够返回前端值
				$resultList['delete_announce_result'] = $this->delete_announce_result_access;
			}else{
				unset($where);
				$where['c_announce_id'] = $announce_id;
				$announceClub->where($where)->delete();

				$resultList['delete_announce_result'] = $this->delete_announce_result_success;
			}
		}

		$this-ajaxReturn($resultList);
	}

	/**
	 * 删除公告 球馆
	 * 返回值：
	 *     delete_announce_result_not_exist
	 *     delete_announce_result_access
	 *     delete_announce_result_success
	 */
	public function gymnasiumdeleteAnnounce(){
		//前端传输数据，获取公告id
		$announce_id = $_POST['announce_id'];

		//实例化公告球馆对照对象
		$announceGymnasium = M('announcement_gymnasium_table');

		//从session获取用户id
		$userId = session('id');

		//删除对应公告
		$where['announce_id'] = $announce_id;
		$count = $user->where($where)->count();
		$where['publisher_id'] = $userId;
		$deleteResult = $user->where($where)->delete();

		if($count == 0){
			$resultList['delete_announce_result'] = $this->delete_announce_result_not_exist;
		}else{
			if(!$deleteResult){
				//权限不够返回前端值
				$resultList['delete_announce_result'] = $this->delete_announce_result_access;
			}else{
				unset($where);
				$where['g_announce_id'] = $announce_id;
				$announceGymnasium->where($where)->delete();

				$resultList['delete_announce_result'] = $this->delete_announce_result_success;
			}
		}

		$this-ajaxReturn($resultList);
	}

	/**
	 * 删除公告 教练
	 * 返回值：
	 *     delete_announce_result_not_exist
	 *     delete_announce_result_access
	 *     delete_announce_result_success
	 */
	public function coachdeleteAnnounce(){
		//前端传输数据，获取公告id
		$announce_id = $_POST['announce_id'];

		//实例化公告球馆对照对象
		$announceCoach = M('announcement_coach_table');

		//从session获取用户id
		$userId = session('id');

		//删除对应公告
		$where['announce_id'] = $announce_id;
		$count = $user->where($where)->count();
		$where['publisher_id'] = $userId;
		$deleteResult = $user->where($where)->delete();

		if($count == 0){
			$resultList['delete_announce_result'] = $this->delete_announce_result_not_exist;
		}else{
			if(!$deleteResult){
				//权限不够返回前端值
				$resultList['delete_announce_result'] = $this->delete_announce_result_access;
			}else{
				unset($where);
				$where['c_announce_id'] = $announce_id;
				$announceCoach->where($where)->delete();

				$resultList['delete_announce_result'] = $this->delete_announce_result_success;
			}
		}

		$this-ajaxReturn($resultList);
	}
	//我的公告
    public function listMyAnnounce()
	{
		//加载当前用户信息
		$user_id=session('id');
		$user=$_SESSION['think_'];
        $this->assign('user',$user);
        //设置当前的选项位置（即该选项为橙色)
        $this->assign("biz_item_num",14);	
	    $announce=M('Announcement_table');
    	$list = $announce->where("publisher_id=%d",$user_id)->select();
    	$this->data = $list; 
    	$this->display(); 
	}
	 //删除公告
	 public function deleteAnnounce()
	 {
		 $announce = M('announcement_table');
		//从前端获取公告id
		$where['announce_id'] = $_POST['announce_id'];	
		$deleteResult = $announce->where($where)->delete();
		if ($deleteResult)
		{
		$resultList['msg'] = 0;
		}else{
			$resultList['msg'] = 1;
		}
		$this->ajaxReturn($resultList);
	 }
	/**
	 * 测试ajax返回
	 */
	//公告详情（管理端）
	public function announceDetail()
	{
		$announce_id=$_POST['announce_id'];
		$announce=M('announcement_table');
		$result=$announce->where("announce_id='%d'",$announce_id)->find();
		$resultList["result"]=$result;
		$this->ajaxReturn($resultList);
	}
	//修改公告
	public function updateAnnounce()
	{
		 $upload = new \Org\Net\UploadFile();  
          $upload->maxSize = 3145728;  
          //设置文件上传类型  
          $upload->allowExts = array('jpg','gif','png','jpeg');  
          //设置文件上传位置  
          //$upload->savePath = __PUBLIC__."/Img/Uploads/";
          $upload->savePath = "./Public/Img/Uploads/AnnounceImg/";  
          //设置文件上传名(按照时间)  
          $upload->saveRule = "time";  
          if (!$upload->upload()){ 
   
          }else{  
              //上传成功，获取上传信息  
              $info = $upload->getuploadFileInfo();
              $savename = $info[0]['savename'];
              $imgurl = "/Public/Img/Uploads/AnnounceImg/".$savename;
              $data['announce_picture']=$imgurl;			  
          }
		  $announce=M('announcement_table');
		  $announce_id = $_POST["announce_id"];
		if  ($_POST["announce_title"]!=NULL)
		$data["announce_title"] = $_POST["announce_title"];	 
	    if  ($_POST["announce_content"]!=NULL)
	    $data["announce_content"] = $_POST["announce_content"];
	    if  ($_POST["announce_type"]!=NULL)
		$data["announce_type"]=$_POST["announce_type"];
	     if  ($_POST["if_public"]!=NULL)
		$data["if_public"]=$_POST["if_public"]; 
		 if ($announce->where("announce_id='%d'",$announce_id)->save($data))
			{
				$this->success("修改成功");
			}
	}
	//公告类型切换（管理端）
	public function changeType()
	{
		$user=$_SESSION['think_'];
        $this->assign('user',$user);
		$select_announce=$_POST["announce_select"];
		$user_id=session('id');
		$this->assign("biz_item_num",14);	
	    $announce=M('announcement_table');	
    	$list = $announce->where("announce_type='%d' and publisher_id='%d'",array($select_announce,$user_id))->select();
		$this->data = $list;	
		$this->display('listMyAnnounce');
	}
	public function testAjaxReturn(){
		$data['status']  = 1;
		$data['content'] = 'content';
		$this->ajaxReturn($data);
	}
}